package com.ikangtai.shecare.common.services.ble;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.Conversion;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.FormatUtil;
import com.ikangtai.shecare.personal.MyDeviceActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@SuppressLint("NewApi")
public class BLEThermometerService extends Service {

	private static final String TAG = BLEThermometerService.class.getSimpleName();

	public static enum TemperatureUnit {
		UNKNOWN_UNIT, CELSIUS_DEGREE, FAHRENHEIT_DEGREE;
	}

	public static enum ThermometerDataTag {
		TEMPERATURE_MEASUREMENT_DATA_FLAG(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_DATA_FLAG"),
		TEMPERATURE_MEASUREMENT_DATA_YEAR(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_DATA_YEAR"),
		TEMPERATURE_MEASUREMENT_DATA_MONTH(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_DATA_MONTH"),
		TEMPERATURE_MEASUREMENT_DATA_DAY(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_DATA_DAY"),
		TEMPERATURE_MEASUREMENT_DATA_HOUR(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_DATA_HOUR"),
		TEMPERATURE_MEASUREMENT_DATA_MIN(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_DATA_MIN"),
		TEMPERATURE_MEASUREMENT_DATA(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_DATA"),
		MANUFACTURE_NAME_DATA(
				"com.ikangtai.bluetooth.le.MANUFACTURE_NAME_DATA"),
		MODEL_NUMBER_DATA(
				"com.ikangtai.bluetooth.le.MODEL_NUMBER_DATA"),
		SERIAL_NUMBER_DATA(
				"com.ikangtai.bluetooth.le.SERIAL_NUMBER_DATA"),
		HARDWARE_REVISION_DATA(
				"com.ikangtai.bluetooth.le.HARDWARE_REVISION_DATA"),
		FIRMWARE_REVISION_DATA(
				"com.ikangtai.bluetooth.le.FIRMWARE_REVISION_DATA"),
		SOFTWARE_REVISION_DATA(
				"com.ikangtai.bluetooth.le.SOFTWARE_REVISION_DATA"),
		BIND_PHONE_DATA(
				"com.ikangtai.bluetooth.le.BIND_PHONE_DATA"),
		OAD_IMAGE_REVISION_DATA(
				"com.ikangtai.bluetooth.le.OAD_IMAGE_REVISION_DATA"),
		OAD_IMAGE_BLOCK_REQUEST_DATA(
				"com.ikangtai.bluetooth.le.OAD_IMAGE_BLOCK_REQUEST_DATA"),
		CLOSE_THERMOMETER_DATA(
				"com.ikangtai.bluetooth.le.CLOSE_THERMOMETER_DATA"),
		SYNC_TIME_DATA(
				"com.ikangtai.bluetooth.le.SYNC_TIME_DATA"),
		RSSI_DATA("com.ikangtai.bluetooth.le.RSSI_DATA"),
		TEMPERATURE_UNIT_DATA("com.ikangtai.bluetooth.le.TEMPERATURE_UNIT_DATA"),
		TEMPERATURE_NUM_DATA("com.ikangtai.bluetooth.le.TEMPERATURE_NUM_DATA");
		private String name;
		private ThermometerDataTag(String name) {
			this.name = name;
		}
		public String getName() {
			return this.name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}

	public static enum ThermometerMessage {
		THERMOMETER_FOUND("com.ikangtai.bluetooth.le.THERMOMETER_FOUND"),
		THERMOMETER_CONNECTED("com.ikangtai.bluetooth.le.THERMOMETER_CONNECTED"), 
		THERMOMETER_DISCONNECTED(
				"com.ikangtai.bluetooth.le.THERMOMETER_DISCONNECTED"),
		TEMPERATURE_MEASUREMENT_SERVICE_FOUND(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_SERVICE_FOUND"), 
		DEVICE_INFORMATION_SERVICE_FOUND(
				"com.ikangtai.bluetooth.le.DEVICE_INFORMATION_SERVICE_FOUND"),
		TEMPERATURE_MEASUREMENT_FOUND(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_FOUND"), 
		INTERMEDIATE_TEMPERATURE_FOUND(
				"com.ikangtai.bluetooth.le.INTERMEDIATE_TEMPERATURE_FOUND"), 
		TEMPERATURE_TYPE_FOUND(
				"com.ikangtai.bluetooth.le.TEMPERATURE_TYPE_FOUND"), 
		MEASUREMENT_INTERVAL_FOUND(
				"com.com.ikangtai.bluetooth.le.MEASUREMENT_INTERVAL_FOUND"), 
		MANUFACTURER_NAME_FOUND(
				"com.ikangtai.bluetooth.le.MANUFACTURER_NAME_FOUND"), 
		MODEL_NUMBER_FOUND(
				"com.ikangtai.bluetooth.le.MODEL_NUMBER_FOUND"), 
		SERIAL_NUMBER_FOUND(
				"com.ikangtai.bluetooth.le.SERIAL_NUMBER_FOUND"), 
		HARDWARE_REVISION_FOUND(
				"com.ikangtai.bluetooth.le.HARDWARE_REVISION_FOUND"), 
		BIND_PHONE_FOUND(
				"com.ikangtai.bluetooth.le.BIND_PHONE_FOUND"),
		SYSTEM_ID_FOUND(
				"com.ikangtai.bluetooth.le.SYSTEM_ID_FOUND"), 
		FIRMWARE_REVISION_FOUND(
				"com.ikangtai.bluetooth.le.FIRMWARE_REVISION_FOUND"), 
		FIRMWARE_TIMESYNC_FOUND(
				"com.ikangtai.bluetooth.le.FIRMWARE_TIMESYNC_FOUND"),
		FIRMWARE_ALARMSETTING_FOUND(
				"com.ikangtai.bluetooth.le.FIRMWARE_ALARMSETTING_FOUND"),
		SOFTWARE_REVISION_FOUND(
				"com.ikangtai.bluetooth.le.SOFTWARE_REVISION_FOUND"),
		OAD_IMAGE_REVISION_READ(
				"com.ikangtai.bluetooth.le.OAD_IMAGE_REVISION_READ"),
		OAD_IMAGE_BLOCK_REQUEST_READ(
				"com.ikangtai.bluetooth.le.OAD_IMAGE_BLOCK_REQUEST_READ"),
		TEMPERATURE_MEASUREMENT_OPEN(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_OPEN"), 
		TEMPERATURE_MEASUREMENT_CLOSE(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_CLOSE"), 
		INTERMEDIATE_TEMPERATURE_OPEN(
				"com.ikangtai.bluetooth.le.INTERMEDIATE_TEMPERATURE_OPEN"),
		TEMPERATURE_MEASUREMENT_READ(
				"com.ikangtai.bluetooth.le.TEMPERATURE_MEASUREMENT_READ"), 
		INTERMEDIATE_TEMPERATURE_READ(
				"com.ikangtai.bluetooth.le.INTERMEDIATE_TEMPERATURE_READ"),
		MANUFACTURER_NAME_READ(
				"com.ikangtai.bluetooth.le.MANUFACTURER_NAME_READ"), 
		MODEL_NUMBER_READ(
				"com.ikangtai.bluetooth.le.MODEL_NUMBER_READ"), 
		SERIAL_NUMBER_READ(
				"com.ikangtai.bluetooth.le.SERIAL_NUMBER_READ"), 
		HARDWARE_REVISION_READ(
				"com.ikangtai.bluetooth.le.HARDWARE_REVISION_READ"), 
		FIRMWARE_REVISION_READ(
				"com.ikangtai.bluetooth.le.FIRMWARE_REVISION_READ"), 
		SOFTWARE_REVISION_READ(
				"com.ikangtai.bluetooth.le.SOFTWARE_REVISION_READ"),
		CLOSE_THERMOMETER_FOUND(
				"com.ikangtai.bluetooth.le.CLOSE_THERMOMETER_FOUND"),
		RSSI_DATA_AVAILABLE("com.ikangtai.bluetooth.le.RSSI_DATA_AVAILABLE");

		private String name;
		private ThermometerMessage(String name) {
			this.name = name;
		}
		public String getName() {
			return this.name;
		}
		public void setName(String name) {
			this.name = name;
		}
	}

	private BluetoothManager mBluetoothManager = null;
	private BluetoothAdapter mBluetoothAdapter = null;
	private int mConnectionState = 0;
	public static ArrayList<BluetoothDevice> thermometers = new ArrayList();
	public BluetoothDevice activeThermometer = null;
	private BluetoothGatt mBluetoothGatt = null;
	public boolean autoConnect = true;
	private final IBinder mBinder = new LocalBinder();
	private BluetoothGattCharacteristic temperatureMeasurementCharacteristic = null;
	private BluetoothGattCharacteristic temperatureTypeCharacteristic = null;
	private BluetoothGattCharacteristic manufacturerNameCharacteristic = null;
	private BluetoothGattCharacteristic modelNumberCharacteristic = null;
	private BluetoothGattCharacteristic serialNumberCharacteristic = null;
	private BluetoothGattCharacteristic hardwareRevisionCharacteristic = null;
	private BluetoothGattCharacteristic firmwareRevisionCharacteristic = null;
	private BluetoothGattCharacteristic firmwareTimeSyncCharacteristic = null;
	private BluetoothGattCharacteristic firmwareAlarmSettingCharacteristic = null;
	private BluetoothGattCharacteristic softwareRevisionCharacteristic = null;
	private BluetoothGattCharacteristic systemIDCharacteristic = null;
	private BluetoothGattCharacteristic deviceNameCharacteristic = null;
	private BluetoothGattCharacteristic bindPhoneCharacteristic = null;
	private BluetoothGattCharacteristic temperatureClearCharacteristic = null;
	private BluetoothGattCharacteristic oADImageRevisionCharacteristic = null;
	private BluetoothGattCharacteristic oADImageBlockRequestCharacteristic = null;
	private BluetoothGattCharacteristic pregnantPeriodCharacterristic = null;
	private BluetoothGattCharacteristic connControlCharacteristic = null;
	private volatile boolean mBusy = false; // Write/read pending response

	@SuppressLint("NewApi")
	private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {

		public void onConnectionStateChange(BluetoothGatt gatt, int status,int newState) {

			AppLog.e("onConnectionStateChange status = " + status + ", newState = " + newState);

			if (newState == 2) {
				String intentAction = BLEThermometerService.ThermometerMessage.THERMOMETER_CONNECTED.getName();
				BLEThermometerService.this.mConnectionState = 2;
				BLEThermometerService.this.broadcastUpdate(intentAction);
				BLEThermometerService.this.getAllServicesFromThermometer();
			} else if (newState == 0) {
				String intentAction = BLEThermometerService.ThermometerMessage.THERMOMETER_DISCONNECTED
						.getName();
				thermometers.clear();
				BLEThermometerService.this.mConnectionState = 0;
				BLEThermometerService.this.broadcastUpdate(intentAction);
				gatt.close();
			} else if (newState == 1) {
				BLEThermometerService.this.mConnectionState = 1;
			} else if (newState == 3) {
				BLEThermometerService.this.mConnectionState = 3;
			}
		}

		public void onServicesDiscovered(BluetoothGatt gatt, int status) {
			if (status == BluetoothGatt.GATT_SUCCESS) {
				List<BluetoothGattService> mServiceList = gatt.getServices();
				for(int i = 0; i < mServiceList.size(); i++){
					AppLog.e("mServiceList" + mServiceList.get(i).getUuid().toString());
				}
				BluetoothGattService _l_service = null;
				//初始化温度服务
				_l_service = BLEThermometerService.this.mBluetoothGatt.getService(UUID.fromString(BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_SERVICE_UUID));
				if (_l_service != null) {
					sendBroadcastAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_SERVICE_FOUND.getName());
					BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_TEMPERATURE_MEASUREMENT_CHARACTERISTIC_UUID));
					if (characteristic != null) {
						BLEThermometerService.this.temperatureMeasurementCharacteristic = characteristic;
						BLEThermometerService.this.setBLEThermometerTemperatureMeasurementSwitch(true);
						sendBroadcastAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_FOUND.getName());
					}

					initFirmwareTimeSyncCharacteristic(_l_service, BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_TIME_SYNC_CHARACTERISTIC_UUID, null);
					BLEThermometerService.this.bindPhoneCharacteristic = null;
					initBindPhoneCharacteristic(_l_service, BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_BIND_PHONE_CHARACTERISTIC_UUID, null);
					BLEThermometerService.this.temperatureClearCharacteristic = null;
					initTemperatureClearCharacteristic(_l_service,BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_TEMPERATURE_CLEAR_CHARACTERISTIC_UUID,null);
					initPregnantPeriodCharacteristic(_l_service, BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_PREGNENT_PERIOD_CHARACTERISTIC_UUID, null);
					initTemperatureTypeCharacteristic(_l_service,BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_TEMPERATURE_TYPE_CHARACTERISTIC_UUID,BLEThermometerService.ThermometerMessage.TEMPERATURE_TYPE_FOUND.getName());
				  }
				//初始化设备信息服务
				_l_service = BLEThermometerService.this.mBluetoothGatt.getService(UUID.fromString(BLEThermometerParameters.BLE_DEVICE_INFORMATION_SERVICE_UUID));
				if (_l_service != null) {
					sendBroadcastAction(BLEThermometerService.ThermometerMessage.DEVICE_INFORMATION_SERVICE_FOUND.getName());
					initManufacturerNameCharacteristic(_l_service, BLEThermometerParameters.BLE_DEVICE_INFORMATION_MANUFACTURER_NAME_CHARACTERISTIC_UUID, BLEThermometerService.ThermometerMessage.MANUFACTURER_NAME_FOUND.getName());
					initModelNumberCharacteristic(_l_service, BLEThermometerParameters.BLE_DEVICE_INFORMATION_MODEL_NUMBER_CHARACTERISTIC_UUID, BLEThermometerService.ThermometerMessage.MODEL_NUMBER_FOUND.getName());
					initSerialNumberCharacteristic(_l_service, BLEThermometerParameters.BLE_DEVICE_INFORMATION_SERIAL_NUMBER_CHARACTERISTIC_UUID, BLEThermometerService.ThermometerMessage.SERIAL_NUMBER_FOUND.getName());
					initHardwareRevisionCharacteristic(_l_service, BLEThermometerParameters.BLE_DEVICE_INFORMATION_HARDWARE_REVISION_CHARACTERISTIC_UUID, BLEThermometerService.ThermometerMessage.HARDWARE_REVISION_FOUND.getName());
					initFirmwareRevisionCharacteristic(_l_service, BLEThermometerParameters.BLE_DEVICE_INFORMATION_FIRMWARE_REVISION_CHARACTERISTIC_UUID, BLEThermometerService.ThermometerMessage.FIRMWARE_REVISION_FOUND.getName());
					initSoftwareRevisionCharacteristic(_l_service, BLEThermometerParameters.BLE_DEVICE_INFORMATION_SOFTWARE_REVISION_CHARACTERISTIC_UUID, BLEThermometerService.ThermometerMessage.SOFTWARE_REVISION_FOUND.getName());
					initSystemIDCharacteristic(_l_service,BLEThermometerParameters.BLE_DEVICE_INFORMATION_SYSTEM_ID_CHARACTERISTIC_UUID,BLEThermometerService.ThermometerMessage.SYSTEM_ID_FOUND.getName());
				}

				//初始化OAD服务
				_l_service = BLEThermometerService.this.mBluetoothGatt.getService(UUID.fromString(BLEThermometerParameters.BLE_DEVICE_INFORMATION_OAD_SERVICE_UUID));
				if (_l_service != null) {
					AppLog.e("BLE_DEVICE_OAD_SERVICE_UUID found");
					initOADImageRevisionCharacteristic(_l_service, BLEThermometerParameters.BLE_DEVICE_INFORMATION_OAD_IMAGE_REVISION_CHARACTERISTIC_UUID, null);
					initOADImageBlockRequestCharacteristic(_l_service, BLEThermometerParameters.BLE_DEVICE_INFORMATION_OAD_IMAGE_BLOCK_REQUEST_CHARACTERISTIC_UUID, null);
				}

				//为了做OAD， CC = Connnect Control
				_l_service = BLEThermometerService.this.mBluetoothGatt.getService(UUID.fromString(BLEThermometerParameters.BLE_DEVICE_INFORMATION_CC_SERVICE_UUID));
				if (_l_service != null) {
					AppLog.e("BLE_DEVICE_CC_SERVICE_UUID found");
					List<BluetoothGattCharacteristic> mCharListCc = _l_service.getCharacteristics();
					connControlCharacteristic = mCharListCc.get(1);
					AppLog.e("connControlCharacteristic uuid" + connControlCharacteristic.getUuid().toString());
				}else{
					AppLog.e("BLE_DEVICE_CC_SERVICE_UUID not found");
				}

			}
		}
		private void initFirmwareTimeSyncCharacteristic(BluetoothGattService _l_service, String UUIDString, String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				firmwareTimeSyncCharacteristic = characteristic;
				mBluetoothGatt.setCharacteristicNotification(firmwareTimeSyncCharacteristic, true);
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initBindPhoneCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				bindPhoneCharacteristic = characteristic;
				mBluetoothGatt.setCharacteristicNotification(bindPhoneCharacteristic, true);
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initTemperatureClearCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				temperatureClearCharacteristic = characteristic;
				mBluetoothGatt.setCharacteristicNotification(temperatureClearCharacteristic, true);
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initTemperatureTypeCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				temperatureTypeCharacteristic = characteristic;
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initManufacturerNameCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				manufacturerNameCharacteristic = characteristic;
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initModelNumberCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				modelNumberCharacteristic = characteristic;
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initSerialNumberCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				serialNumberCharacteristic = characteristic;
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initHardwareRevisionCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				hardwareRevisionCharacteristic = characteristic;
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initSoftwareRevisionCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				softwareRevisionCharacteristic = characteristic;
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initFirmwareRevisionCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				firmwareRevisionCharacteristic = characteristic;
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}

		private void initSystemIDCharacteristic(BluetoothGattService _l_service, String UUIDString,String intentAction){

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				systemIDCharacteristic = characteristic;
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}

		private void initPregnantPeriodCharacteristic(BluetoothGattService _l_service, String UUIDString, String intentAction) {

			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				pregnantPeriodCharacterristic = characteristic;
				mBluetoothGatt.setCharacteristicNotification(pregnantPeriodCharacterristic, true);
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}


		private void initOADImageRevisionCharacteristic(BluetoothGattService _l_service, String UUIDString, String intentAction) {
			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				oADImageRevisionCharacteristic = characteristic;
				oADImageRevisionCharacteristic.setWriteType(BluetoothGattCharacteristic.PROPERTY_NOTIFY);
				mBluetoothGatt.setCharacteristicNotification(oADImageRevisionCharacteristic, true);
				AppLog.e("oADImageRevisionCharacteristic" + oADImageRevisionCharacteristic.toString());
//				BluetoothGattDescriptor descriptor = oADImageRevisionCharacteristic
//						.getDescriptor(UUID
//								.fromString(BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR));
//				descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
//				mBluetoothGatt.writeDescriptor(descriptor);
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}
		private void initOADImageBlockRequestCharacteristic(BluetoothGattService _l_service, String UUIDString, String intentAction) {
			BluetoothGattCharacteristic characteristic = _l_service.getCharacteristic(UUID.fromString(UUIDString));
			if (characteristic != null) {
				oADImageBlockRequestCharacteristic = characteristic;
				//mBluetoothGatt.setCharacteristicNotification(oADImageBlockRequestCharacteristic, false);
				oADImageBlockRequestCharacteristic.setWriteType(BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE);
				AppLog.e("oADImageBlockRequestCharacteristic" + oADImageBlockRequestCharacteristic.toString());
				if(null!=intentAction)
					sendBroadcastAction(intentAction);
			}
		}

		public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
			AppLog.i("onCharacteristicRead status:" + status);
			if (status != 0) {
				return;
			}
			if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_HARDWARE_REVISION_CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString())) {
				String characteristicValue = characteristic.getStringValue(0);
				AppLog.i("hardwareRevision onCharacteristicRead characteristicValue:"+characteristicValue);
				readHardwareRevisionCharacteristic(characteristicValue, BLEThermometerService.ThermometerMessage.HARDWARE_REVISION_READ.getName(), BLEThermometerService.ThermometerDataTag.HARDWARE_REVISION_DATA.getName());
			} else if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_MANUFACTURER_NAME_CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString())) {
				readCharacteristic(characteristic, BLEThermometerService.ThermometerMessage.MANUFACTURER_NAME_READ.getName(), BLEThermometerService.ThermometerDataTag.MANUFACTURE_NAME_DATA.getName());
			} else if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_MODEL_NUMBER_CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString())) {
				readCharacteristic(characteristic, BLEThermometerService.ThermometerMessage.MODEL_NUMBER_READ.getName(), BLEThermometerService.ThermometerDataTag.MODEL_NUMBER_DATA.getName());
			} else if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_SERIAL_NUMBER_CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString())) {
				readCharacteristic(characteristic, BLEThermometerService.ThermometerMessage.SERIAL_NUMBER_READ.getName(), BLEThermometerService.ThermometerDataTag.SERIAL_NUMBER_DATA.getName());
			} else if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_FIRMWARE_REVISION_CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString())) {
				readCharacteristic(characteristic, BLEThermometerService.ThermometerMessage.FIRMWARE_REVISION_READ.getName(), BLEThermometerService.ThermometerDataTag.FIRMWARE_REVISION_DATA.getName());
			} else if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_SOFTWARE_REVISION_CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString())) {
				readCharacteristic(characteristic, BLEThermometerService.ThermometerMessage.SOFTWARE_REVISION_READ.getName(), BLEThermometerService.ThermometerDataTag.SOFTWARE_REVISION_DATA.getName());
			} else if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_OAD_IMAGE_REVISION_CHARACTERISTIC_UUID.equals(characteristic.getUuid().toString())) {
				AppLog.e("BLE_DEVICE_INFORMATION_OAD_IMAGE_REVISION_CHARACTERISTIC_UUID read");
				//readCharacteristic(characteristic, ThermometerMessage.OAD_IMAGE_REVISION_READ.getName(), BLEThermometerService.ThermometerDataTag.OAD_IMAGE_REVISION_DATA.getName());
			}
		}

		private void readCharacteristic(BluetoothGattCharacteristic characteristic, String intentNane, String StringExtraName) {
			String characteristicValue = characteristic.getStringValue(0);
			Intent intent = new Intent(intentNane);
			intent.putExtra(StringExtraName, characteristicValue);
			BLEThermometerService.this.sendBroadcast(intent);
		}
		private void readHardwareRevisionCharacteristic(String characteristicValue, String intentNane, String StringExtraName) {
			Intent intent = new Intent(intentNane);
			intent.putExtra(StringExtraName, characteristicValue);
			BLEThermometerService.this.sendBroadcast(intent);
		}

		public void onCharacteristicWrite(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic, int status) {
			if (status != 0) {
				return;
			}
			if (BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_TIME_SYNC_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				writeCharacteristicDescriptor(firmwareTimeSyncCharacteristic);
			}
			if (BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_ALARM_SETTING_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				writeCharacteristicDescriptor(firmwareAlarmSettingCharacteristic);
			}
			if (BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_TEMPERATURE_CLEAR_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())){
				writeCharacteristicDescriptor(temperatureClearCharacteristic);
			}
			if(BLEThermometerParameters.BLE_DEVICE_INFORMATION_OAD_IMAGE_REVISION_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())){
				mBusy = false;
				AppLog.e("OAD_IMAGE_BLOCK_REQUEST writeDescriptor" + status);
				//writeCharacteristicDescriptor(oADImageRevisionCharacteristic);
				BluetoothGattDescriptor descriptor = oADImageRevisionCharacteristic
						.getDescriptor(UUID
								.fromString(BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR));
				descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
				boolean result = mBluetoothGatt.writeDescriptor(descriptor);
				AppLog.e("OAD_IMAGE_BLOCK_REQUEST writeDescriptor" + result);
			}
			if(BLEThermometerParameters.BLE_DEVICE_INFORMATION_OAD_IMAGE_BLOCK_REQUEST_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())){
				AppLog.e("OAD_IMAGE_BLOCK_REQUEST");
				//writeCharacteristicDescriptor(oADImageBlockRequestCharacteristic);
			}
			if (BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_PREGNENT_PERIOD_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				writeCharacteristicDescriptor(pregnantPeriodCharacterristic);
			}
		}

		private void writeCharacteristicDescriptor(BluetoothGattCharacteristic Characteristic) {
			if(null == bindPhoneCharacteristic){
				BluetoothGattDescriptor descriptor = Characteristic
						.getDescriptor(UUID
								.fromString(BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR));
				descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
				boolean result = mBluetoothGatt.writeDescriptor(descriptor);
			}
		}

		public void onCharacteristicChanged(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic) {
			if (BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_TIME_SYNC_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				parseFeedbackResultFromThermometer(characteristic,BLEThermometerService.ThermometerMessage.FIRMWARE_TIMESYNC_FOUND.getName(),BLEThermometerService.ThermometerDataTag.SYNC_TIME_DATA
						.getName());
			}
			if (BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_BIND_PHONE_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				parseFeedbackResultFromThermometer(characteristic,BLEThermometerService.ThermometerMessage.BIND_PHONE_FOUND
						.getName(),BLEThermometerService.ThermometerDataTag.BIND_PHONE_DATA
						.getName());
			}
			if (BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_TEMPERATURE_CLEAR_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				parseFeedbackResultFromThermometer(characteristic,BLEThermometerService.ThermometerMessage.CLOSE_THERMOMETER_FOUND
						.getName(),BLEThermometerService.ThermometerDataTag.CLOSE_THERMOMETER_DATA
						.getName());
			}
			if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_OAD_IMAGE_REVISION_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				AppLog.e("BLE_DEVICE_INFORMATION_OAD_IMAGE_REVISION_CHARACTERISTIC_UUID onCharacteristicChanged");
				parseFeedbackResultFromThermometer(characteristic, BLEThermometerService.ThermometerMessage.OAD_IMAGE_REVISION_READ
						.getName(), ThermometerDataTag.OAD_IMAGE_REVISION_DATA
						.getName());
			}
			if (BLEThermometerParameters.BLE_DEVICE_INFORMATION_OAD_IMAGE_BLOCK_REQUEST_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				parseFeedbackResultFromThermometer(characteristic, ThermometerMessage.OAD_IMAGE_BLOCK_REQUEST_READ
						.getName(), ThermometerDataTag.OAD_IMAGE_BLOCK_REQUEST_DATA
						.getName());
			}
			if (BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_TEMPERATURE_MEASUREMENT_CHARACTERISTIC_UUID
					.equals(characteristic.getUuid().toString())) {
				parseThermometer(characteristic);
			}
		}

		private void parseFeedbackResultFromThermometer(BluetoothGattCharacteristic characteristic,String intentString, String intentExtra) {
			byte[] _l_byte_arr_value = characteristic.getValue();
			if(null!=_l_byte_arr_value){
				//byte Thermometer_result = _l_byte_arr_value[3];
				if (BLEThermometerParameters.BLE_YUNBI_HEALTHY_THERMOMETER_TEMPERATURE_CLEAR_CHARACTERISTIC_UUID
						.equals(characteristic.getUuid().toString())){
					byte Thermometer_result = _l_byte_arr_value[4];
					float result = Thermometer_result & 0xff;
					String intent_action = intentString;
					Intent intent = new Intent(intent_action);
					intent.putExtra(
							intentExtra, result);
					BLEThermometerService.this.sendBroadcast(intent);
				}else{
					byte Thermometer_result = _l_byte_arr_value[3];
					int result = Thermometer_result & 0xff;
					String intent_action = intentString;
					Intent intent = new Intent(intent_action);
					intent.putExtra(
							intentExtra, result);
					BLEThermometerService.this.sendBroadcast(intent);
				}
			}
		}

		public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {}

		public void onDescriptorWrite(BluetoothGatt gatt,
				BluetoothGattDescriptor descriptor, int status) {
			if (status == 0) {
				if (descriptor
						.getCharacteristic()
						.getUuid()
						.toString()
						.equals(BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_TEMPERATURE_MEASUREMENT_CHARACTERISTIC_UUID)) {

					Intent intent = null;
					if ((descriptor.getValue()[0] & 0x2) != 0)
					{
						intent = new Intent(
								BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_OPEN
										.getName());
						if(App.isBindActivityActive) intent.putExtra("isInBind", 1);
					}
					else {
						intent = new Intent(
								BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_CLOSE
										.getName());
					}
					BLEThermometerService.this.sendBroadcast(intent);
				}
			}

		}
	};


	private void parseThermometer(BluetoothGattCharacteristic characteristic) {

			byte[] _l_byte_arr_value = characteristic.getValue();

			for (int i = 0; i < _l_byte_arr_value.length; i++) {
			}
			int Thermometer_flag_num;
			byte Thermometer_flag = _l_byte_arr_value[0];

			if ((Thermometer_flag & 0x10) != 0) {
				Thermometer_flag_num = 0;
			} else if ((Thermometer_flag & 0x20) != 0) {
				Thermometer_flag_num = 1;
			} else {
				Thermometer_flag_num = 2;
			}
			//一代温度数据解析
			if(null==bindPhoneCharacteristic){
				byte Thermometer_low = _l_byte_arr_value[1];
				byte Thermometer_high = _l_byte_arr_value[2];
				double thermometer = Thermometer_high * 16 * 16
						+ (Thermometer_low & 0xff);

				byte Thermometer_year_low = _l_byte_arr_value[5];
				byte Thermometer_year_high = _l_byte_arr_value[6];
				int year = Thermometer_year_high * 16 * 16
						+ (Thermometer_year_low & 0xff);

				byte Thermometer_month = _l_byte_arr_value[7];
				int month = Thermometer_month & 0xff;

				byte Thermometer_day = _l_byte_arr_value[8];
				int day = Thermometer_day & 0xff;

				byte Thermometer_hour = _l_byte_arr_value[9];
				int hour = Thermometer_hour & 0xff;

				byte Thermometer_min = _l_byte_arr_value[10];
				int min = Thermometer_min & 0xff;

				byte flag = _l_byte_arr_value[0];
				BLEThermometerService.TemperatureUnit _l_tem_unit;
				if ((flag & 0x1) != 0)
					_l_tem_unit = BLEThermometerService.TemperatureUnit.FAHRENHEIT_DEGREE;
				else {
					_l_tem_unit = BLEThermometerService.TemperatureUnit.CELSIUS_DEGREE;
				}

				int temperature_measurement_origin = characteristic
						.getIntValue(20, 1).intValue();

				byte exponent = (byte) (temperature_measurement_origin >> 24);
				int mantissa = temperature_measurement_origin & 0xFFFFFF;

				if (temperature_measurement_origin == 8388607) {
					AppLog.e("Invalid temperature value received.");
				}
				Intent intent = new Intent(
						BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_READ
								.getName());

				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_FLAG
								.getName(), Thermometer_flag_num);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_YEAR
								.getName(), year);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_MONTH
								.getName(), month);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_DAY
								.getName(), day);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_HOUR
								.getName(), hour);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_MIN
								.getName(), min);

				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA
								.getName(),
						mantissa * Math.pow(10.0D, exponent));
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_UNIT_DATA
								.getName(), _l_tem_unit);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_NUM_DATA
								.getName(), -1); //1代温度数量不统计使用负数表示
				BLEThermometerService.this.sendBroadcast(intent);
			}else {
				byte Thermometer_high = _l_byte_arr_value[3];
				double high = Thermometer_high & 0xff;
				byte Thermometer_low = _l_byte_arr_value[4];
				double low = Thermometer_low & 0xff;
				double temperature = high + low / 100;

				byte Thermometer_year_low = _l_byte_arr_value[5];
				byte Thermometer_year_high = _l_byte_arr_value[6];
				int year = Thermometer_year_high * 16 * 16
						+ (Thermometer_year_low & 0xff);

				byte Thermometer_month = _l_byte_arr_value[7];
				int month = Thermometer_month & 0xff;

				byte Thermometer_day = _l_byte_arr_value[8];
				int day = Thermometer_day & 0xff;

				byte Thermometer_hour = _l_byte_arr_value[9];
				int hour = Thermometer_hour & 0xff;

				byte Thermometer_min = _l_byte_arr_value[10];
				int min = Thermometer_min & 0xff;

				byte Thermometer_num = _l_byte_arr_value[11];
				int num = Thermometer_num & 0xff;

				AppLog.i("temper month:" + month + "day: " + day);
//				if (month == 0) {
//					year -= 1;
//					month = 12;
//				}
//				if(month==1&&day==0){
//					year -= 1;
//					month = 12;
//					day=31;
//				}
				byte flag = _l_byte_arr_value[0];
				BLEThermometerService.TemperatureUnit _l_tem_unit;
				if ((flag & 0x1) != 0)
					_l_tem_unit = BLEThermometerService.TemperatureUnit.FAHRENHEIT_DEGREE;
				else {
					_l_tem_unit = BLEThermometerService.TemperatureUnit.CELSIUS_DEGREE;
				}

				Intent intent = new Intent(
						BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_READ
								.getName());
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_FLAG
								.getName(), Thermometer_flag_num);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_YEAR
								.getName(), year);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_MONTH
								.getName(), month + 1); //硬件月份数比实际值小1
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_DAY
								.getName(), day + 1);  //硬件日期比实际值小1
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_HOUR
								.getName(), hour);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA_MIN
								.getName(), min);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_MEASUREMENT_DATA
								.getName(),
						temperature);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_UNIT_DATA
								.getName(), _l_tem_unit);
				intent.putExtra(
						BLEThermometerService.ThermometerDataTag.TEMPERATURE_NUM_DATA
								.getName(), num);
				BLEThermometerService.this.sendBroadcast(intent);
			}
	}

	private void sendBroadcastAction(String intentAction) {
		Intent intent = new Intent(intentAction);
		BLEThermometerService.this.sendBroadcast(intent);
	}

	@Override
	public boolean bindService(Intent service, ServiceConnection conn, int flags) {
		return super.bindService(service, conn, flags);
	}
	
	private void broadcastUpdate(String action) {
		Intent intent = new Intent(action);
		sendBroadcast(intent);
	}
	
	public class LocalBinder extends Binder {
		public LocalBinder() {}
		public BLEThermometerService getService() {
			return BLEThermometerService.this;
		}
	}

	public IBinder onBind(Intent intent) {
		return this.mBinder;
	}

	public boolean onUnbind(Intent intent) {
		disconnect();
		close();
		return super.onUnbind(intent);
	}

	public void onCreate() {}
 
	public void onDestroy() {
		disconnect();
		close();
	}

	@SuppressLint("NewApi")
	public boolean initialize() {
		if (this.mBluetoothManager == null) {
			this.mBluetoothManager = ((BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE));
			if (this.mBluetoothManager == null) {
				return false;
			}
		}

		if (this.mBluetoothAdapter == null) {
			this.mBluetoothAdapter = this.mBluetoothManager.getAdapter();
			if (this.mBluetoothAdapter == null) {
				return false;
			}

		}

		if (!getPackageManager().hasSystemFeature(
				"android.hardware.bluetooth_le")) {
			return false;
		}
		return true;
	}

	public void openBluetooth(Activity activity) {
		if (!this.mBluetoothAdapter.isEnabled()) {
//			mBluetoothAdapter.enable();
			Intent enableBtIntent = new Intent(
					"android.bluetooth.adapter.action.REQUEST_ENABLE");
			activity.startActivityForResult(enableBtIntent, 1);
		}
	}

	public boolean scanThermometers(LeScanCallback mLeScanCallback) {
		this.thermometers.clear();
		this.activeThermometer = null;

		if (validateBluetoothEnvironment()) {
			UUID[] uuids = { UUID
					.fromString(BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_SERVICE_UUID) };
			if(mBluetoothAdapter!=null){
				mBluetoothAdapter.startLeScan(uuids,mLeScanCallback);
			}

			return true;
		}else
			return false;

	}

	@SuppressWarnings("deprecation")
	public void stopScanThermometers(LeScanCallback mLeScanCallback) {
		if (validateBluetoothEnvironment())
			this.mBluetoothAdapter.stopLeScan(mLeScanCallback);
	}

	@SuppressLint("NewApi")
	public boolean connectThermometer(String address) {
		if ((this.mBluetoothAdapter == null) || (address == null)) {
			return false;
		}

		this.activeThermometer = this.mBluetoothAdapter
				.getRemoteDevice(address);
		if (this.activeThermometer == null) {
			return false;
		}

		this.mBluetoothGatt = this.activeThermometer.connectGatt(this, false,
				this.mGattCallback);
		this.mConnectionState = 1;
		return true;
	}

	public boolean getAllServicesFromThermometer() {
		return this.mBluetoothGatt.discoverServices();
	}

	
	public static boolean checkBind(Context context){

			if(!"".equals(App.getPreference("bind"))){
			 String savedAddresses= App.getPreference("bind");
             String[] bindAddress=savedAddresses.split(",");
				for(int i=0;i<bindAddress.length;i++){
					if(null!=thermometers) {
						if(thermometers.get(0).getAddress().trim().equals(bindAddress[i])) return true;
						else continue;
					}
				}
				return false;
			}
			return false;
	}

	public boolean bindThermometer(){
		AppLog.e("bindThermometer");
    if(null==bindPhoneCharacteristic){
	String bind = mBluetoothGatt.getDevice().getAddress().trim();
	if("".equals(App.getPreference("bind"))){
		App.savePreference("bind", bind);
	}
	else{
		String bindAdd=App.getPreference("bind").trim()+","+bind;
		App.savePreference("bind", bindAdd);
	}
	return true;

}
		byte[] buf=new byte[]{(byte)0x5A,(byte)0x0B,(byte)0x06,(byte) 0x5A,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFA};
		AppLog.e("bindThermometer2代");

		if(bindPhoneCharacteristic.setValue(buf))
		{
			AppLog.e("set value OK");
			mBluetoothGatt.writeCharacteristic(bindPhoneCharacteristic);
			String bind = mBluetoothGatt.getDevice().getAddress().trim();
			if("".equals(App.getPreference("bind"))){
			App.savePreference("bind", bind);}
			else{
			String bindAdd=App.getPreference("bind").trim()+","+bind;
				App.savePreference("bind", bindAdd);
		}
			return true;
		}
		else
		{
			return false;
		}		
	}
	
	public boolean unbindThermometer(){

		if("".equals(App.getPreference("bind"))){
			Toast.makeText(this.getApplicationContext(), "温度计未绑定，请确认。", Toast.LENGTH_SHORT).show();
			return false;
		}
		//一代产品的话
		if(null==bindPhoneCharacteristic){
			String savedAddresses = App.getPreference("bind");
			String[] bindAddress = savedAddresses.split(",");
			if (bindAddress.length == 1) {
				App.savePreference("bind", "");
				return true;
			} else {
				List<String> bindList=new ArrayList<String>();
				for(int i=0;i<bindAddress.length;i++){
					bindList.add(bindAddress[i]);
				}
				for (int i = 0; i < bindList.size(); i++) {
					if (thermometers.get(0).getAddress().trim().equals(bindList.get(i))){
						bindList.remove(i);
						break;}
					else continue;
				}
				savedAddresses= FormatUtil.listToString(bindList);
				App.savePreference("bind", savedAddresses);
				return true;
			}

		}
		if(null!=thermometers) {
			byte[] buf = new byte[]{(byte) 0x5A, (byte) 0x0B, (byte) 0x06, (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFA};
			if (bindPhoneCharacteristic.setValue(buf)) {
				mBluetoothGatt.writeCharacteristic(bindPhoneCharacteristic);
				String savedAddresses = App.getPreference("bind");
				String[] bindAddress = savedAddresses.split(",");
				if (bindAddress.length == 1) {
						App.savePreference("bind", "");
					return true;
				} else {
					List<String> bindList=new ArrayList<String>();
					for(int i=0;i<bindAddress.length;i++){
						bindList.add(bindAddress[i]);
					}
					for (int i = 0; i < bindList.size(); i++) {
							if (thermometers.get(0).getAddress().trim().equals(bindList.get(i))){
								bindList.remove(i);
								break;}
							else continue;
					}
					savedAddresses= FormatUtil.listToString(bindList);
					App.savePreference("bind", savedAddresses);
					return true;
				}
			} else {
				return false;
			}
		}else{
			return false;
		}
	}

	/**Current Time
	 * @return
	 */
	public boolean syncCurrentTime(){

		long time=System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();  
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		Date date1=new Date(time);  
        String dateStr=format.format(date1); 
		int year = Integer.parseInt(""+dateStr.subSequence(2, 4));
		int month = Integer.parseInt(""+dateStr.subSequence(5, 7));
		int day = Integer.parseInt(""+dateStr.subSequence(8, 10));
		int hour = Integer.parseInt(""+dateStr.subSequence(11, 13));
		int minute = Integer.parseInt(""+dateStr.subSequence(14, 16));
		AppLog.i("sync month:" + month + "day: " + day);
		if(null!=bindPhoneCharacteristic){
			month -= 1;
			day  -= 1;
		}
		AppLog.i("sync month:" + month + "day: " + day);
		byte[] buf=new byte[]{(byte)0x5A,0x03,0x05,(byte) year,(byte) month,(byte) day,(byte) hour,(byte) minute,(byte) 0xFA};

		if(null != firmwareTimeSyncCharacteristic && firmwareTimeSyncCharacteristic.setValue(buf))
		{
			boolean result = mBluetoothGatt.writeCharacteristic(firmwareTimeSyncCharacteristic);
			AppLog.e("syncCurrentTime:" + result);
			return true;
		}
		else
		{
			return false;
		}
	}

	public void syncACKTemperatureNum(int num){

		if(null != thermometers){
			byte[] buf=new byte[]{(byte)0x5A,(byte)0x07,(byte)0x06,(byte)0xF2,(byte) num,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFA};
			if(null != temperatureClearCharacteristic && temperatureClearCharacteristic.setValue(buf)){
				boolean result = mBluetoothGatt.writeCharacteristic(temperatureClearCharacteristic);
				AppLog.e("syncACKTemperatureNum" + result + num);
			}

		}
	}

	public void syncPregnantPeriod(long startDay, long endDay){
		if(null != thermometers && null != pregnantPeriodCharacterristic){
			String startDayString = DateUtil.getDateStr2bit(startDay);
			int year = Integer.valueOf(startDayString.split("-")[0].substring(2, 4));
			AppLog.e("year" + year);
			int month = Integer.valueOf(startDayString.split("-")[1]) - 1;
			AppLog.e("month" + month);
			int day = Integer.valueOf(startDayString.split("-")[2]) - 1;
			AppLog.e("day" + day);
			String endDayString = DateUtil.getDateStr2bit(endDay);
			int endMonth = Integer.valueOf(endDayString.split("-")[1]) - 1;
			AppLog.e("endMonth" + endMonth);
			int endDayTime = Integer.valueOf(endDayString.split("-")[2]);
			AppLog.e("endDayTime" + endDayTime);
			byte[] buf=new byte[]{(byte)0x5A,(byte)0x08,(byte)0x06,(byte)year,(byte) month,(byte) day,(byte) endMonth,(byte) endDayTime,(byte) 0xFA};
			if(pregnantPeriodCharacterristic.setValue(buf)){
				boolean result = mBluetoothGatt.writeCharacteristic(pregnantPeriodCharacterristic);
				AppLog.e("writePregnantPeriodCharacterristic:" + result);
			}
		}
	}

	public void getBatteryVolume(){

		if(null != thermometers){
			byte[] buf=new byte[]{(byte)0x5A,(byte)0x07,(byte)0x06,(byte)0xFE,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFA};
			if(null != temperatureClearCharacteristic && temperatureClearCharacteristic.setValue(buf)){
				boolean result = mBluetoothGatt.writeCharacteristic(temperatureClearCharacteristic);
				AppLog.e("getBatteryVolume:" + result);
			}

		}
	}

	public void notifyOADStart(){

		//if(null != thermometers){
			byte[] buf=new byte[]{(byte)0x5A,(byte)0x07,(byte)0x06,(byte)0xFC,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFA};
			AppLog.e("notifyOADStart setValue:" + Arrays.toString(buf));
			if(temperatureClearCharacteristic.setValue(buf)){
				boolean result = mBluetoothGatt.writeCharacteristic(temperatureClearCharacteristic);
				AppLog.e("notifyOADStart" + result);
			}
//			try {
//				Thread.sleep(20);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
		//}
	}

	/**Current Alarm
	 *
	 * @return
	 */
	public boolean syncCurrentAlarm(int hour, int minute){

		byte[] buf=new byte[]{(byte)0x5A,0x04,0x02,(byte) hour,(byte) minute,(byte) 0xFF,(byte) 0xFF,(byte) 0xFF,(byte) 0xFA};
		
		if(firmwareAlarmSettingCharacteristic.setValue(buf)){
			
			mBluetoothGatt.writeCharacteristic(firmwareAlarmSettingCharacteristic);
			return true;
			
		}else{
			return false;
		}
	}

	public boolean closeThermometer(){


		byte[] buf=new byte[]{(byte)0x5A,0x07,0x06,(byte) 0xFB,(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFA};

		if(temperatureClearCharacteristic.setValue(buf)){

			mBluetoothGatt.writeCharacteristic(temperatureClearCharacteristic);
			return true;

		}else{
			return false;
		}
	}

	public boolean setBLEThermometerTemperatureMeasurementSwitch(
			boolean direction) {
		if (this.temperatureMeasurementCharacteristic == null) {
			return false;
		}

		if ((this.mBluetoothAdapter == null) || (this.mBluetoothGatt == null)) {
			return false;
		}

		boolean ret_bool_character_notify = false;
		if (this.mBluetoothGatt.setCharacteristicNotification(
				this.temperatureMeasurementCharacteristic, direction)) {
			ret_bool_character_notify = true;
		}

		boolean ret_bool_descriptor_value_set = false;
		BluetoothGattDescriptor descriptor = this.temperatureMeasurementCharacteristic
				.getDescriptor(UUID
						.fromString(BLEThermometerParameters.BLE_HEALTHY_THERMOMETER_CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR));
		if (direction)
			ret_bool_descriptor_value_set = descriptor
					.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
		else {
			ret_bool_descriptor_value_set = descriptor
					.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
		}

		boolean ret_bool_descriptor_write = this.mBluetoothGatt
				.writeDescriptor(descriptor);
		return (ret_bool_character_notify) && (ret_bool_descriptor_value_set)
				&& (ret_bool_descriptor_write);
	}

	public boolean readHardwareRevision() {
		if (this.hardwareRevisionCharacteristic == null) {
			return false;
		}

		if (this.mBluetoothGatt
				.readCharacteristic(this.hardwareRevisionCharacteristic)) {
			return true;
		}
		return false;
	}

	public boolean readFirmwareRevision() {
		if (this.firmwareRevisionCharacteristic == null) {
			return false;
		}

		if (this.mBluetoothGatt
				.readCharacteristic(this.firmwareRevisionCharacteristic)) {
			return true;
		}
		return false;
	}

	public void setConnectionParameters() {

		if(mBluetoothGatt.setCharacteristicNotification(firmwareTimeSyncCharacteristic, false))
			AppLog.e("firmwareTimeSyncCharacteristic:true");
		if(null != bindPhoneCharacteristic && mBluetoothGatt.setCharacteristicNotification(bindPhoneCharacteristic, false))
			AppLog.e("bindPhoneCharacteristic:true");
		if(mBluetoothGatt.setCharacteristicNotification(temperatureClearCharacteristic, false))
			AppLog.e("temperatureClearCharacteristic:true");
		if(null != bindPhoneCharacteristic && mBluetoothGatt.setCharacteristicNotification(pregnantPeriodCharacterristic, false))
			AppLog.e("pregnantPeriodCharacterristic:true");
		if(mBluetoothGatt.setCharacteristicNotification(temperatureMeasurementCharacteristic, false))
			AppLog.e("temperatureMeasurementCharacteristic:true");

		// Make sure connection interval is long enough for OAD
		byte[] value = {Conversion.loUint16(MyDeviceActivity.OAD_CONN_INTERVAL), Conversion.hiUint16(MyDeviceActivity.OAD_CONN_INTERVAL), Conversion.loUint16(MyDeviceActivity.OAD_CONN_INTERVAL),
				Conversion.hiUint16(MyDeviceActivity.OAD_CONN_INTERVAL), 0, 0, Conversion.loUint16(MyDeviceActivity.OAD_SUPERVISION_TIMEOUT), Conversion.hiUint16(MyDeviceActivity.OAD_SUPERVISION_TIMEOUT)};
		AppLog.e("setConnectionParameters setValue:" + Arrays.toString(value));
		if(connControlCharacteristic.setValue(value)){
			boolean result = this.mBluetoothGatt.writeCharacteristic(connControlCharacteristic);
			AppLog.e("setConnectionParameters:" + result);
		}
	}

	public void writeOADImageRevision() {
		if (this.oADImageRevisionCharacteristic == null) {
			return;
		}
		if(oADImageRevisionCharacteristic.setValue(new byte[]{(byte) 0x00})){
			boolean result = mBluetoothGatt.writeCharacteristic(oADImageRevisionCharacteristic);
			AppLog.e("writeOADImageRevision setValue:0x00" );
			AppLog.e("writeOADImageRevision0: " + result);
			mBusy = true;
			int i = 1;
			while(mBusy && i < 10){
				try {
					if(result == true) break;
					Thread.sleep(10);
					AppLog.e("writeOADImageRevision0: " + i++);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if(i < 10){
				String intent_action = BLEThermometerService.ThermometerMessage.OAD_IMAGE_REVISION_READ
						.getName();
				Intent intent = new Intent(intent_action);
				intent.putExtra(
						ThermometerDataTag.OAD_IMAGE_REVISION_DATA
								.getName(), 0);
				BLEThermometerService.this.sendBroadcast(intent);
				return;
			}

		}

		if(oADImageRevisionCharacteristic.setValue(new byte[]{(byte) 0x01})){
			AppLog.e("writeOADImageRevision setValue:0x01" );
			boolean result = mBluetoothGatt.writeCharacteristic(oADImageRevisionCharacteristic);
			AppLog.e("writeOADImageRequestValue1: " + result);
			mBusy = true;
			int i = 1;
			while(mBusy  && i < 10) {
				try {
					if(result == true) break;
					Thread.sleep(10);
					AppLog.e("writeOADImageRevision1: " + i++);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if(i < 10){
				String intent_action = BLEThermometerService.ThermometerMessage.OAD_IMAGE_REVISION_READ
						.getName();
				Intent intent = new Intent(intent_action);
				intent.putExtra(
						ThermometerDataTag.OAD_IMAGE_REVISION_DATA
								.getName(), 1);
				BLEThermometerService.this.sendBroadcast(intent);
			}

		}

	}

	public void writeOADImageValue(byte[] buf){
		if(oADImageRevisionCharacteristic.setValue(buf)) {
			AppLog.e("writeOADImageValue setValue:" + Arrays.toString(buf));
			boolean result = mBluetoothGatt.writeCharacteristic(oADImageRevisionCharacteristic);
			AppLog.e("writeOADImageValue:" + result);
			mBusy = true;
			int i = 1;
			while (mBusy && i < 20) {
				try {
					if(result == true) break;
					Thread.sleep(10);
					AppLog.e("writeOADImageValue: " + i++);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public boolean writeOADImageRequestValue(byte[] buf){
			if(oADImageBlockRequestCharacteristic.setValue(buf)) {
				AppLog.e("writeOADImageRequestValue setValue:" + Arrays.toString(buf));
				if(mBluetoothGatt.writeCharacteristic(oADImageBlockRequestCharacteristic)){
					//AppLog.e("writeOADImageRequestValue: " + true);
					return  true;
				}
				else  return false;
			}else  return false;
	}

	private void disconnect() {
		if ((this.mBluetoothAdapter == null) || (this.mBluetoothGatt == null)) {
			return;
		}
		this.thermometers.clear();
		this.mBluetoothGatt.disconnect();
	}

	private void close() {
		if (this.mBluetoothGatt == null) {
			return;
		}
		this.mBluetoothGatt.close();
		this.mBluetoothGatt = null;
		this.activeThermometer = null;
	}

	private boolean validateBluetoothEnvironment() {
		if ((this.mBluetoothAdapter == null)
				|| (this.mBluetoothManager == null)) {
			return false;
		}
		return true;
	}
}